package com.mentalhealthplatform.global.rbac.model;

import com.mentalhealthplatform.global.log.login.LoginLog;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;

import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

@Getter
@Setter
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "user_type", discriminatorType = DiscriminatorType.STRING)
public class User {
    @Id
    @GeneratedValue
    private UUID id;

    @Column(unique = true, nullable = false)
    private String username;

    @Column(nullable = false)
    private String password;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name = "user_roles",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "role_id")
    )
    private Set<Role> roles = new HashSet<>();

    @Column(nullable = false)
    private boolean status = true;

    @Column()
    private String phone;


    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<LoginLog> loginLogs;

    // 构造方法
    public User() {
    }

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    // 添加角色
    public void addRole(Role role) {
        roles.add(role);
    }

    // 移除角色
    public void removeRole(Role role) {
        roles.remove(role);
    }

    // 更改状态
    public void toggleStatus() {
        this.status = !this.status;
    }

    public Set<Menu> getAllMenus() {
        Set<Menu> allMenus = new HashSet<>();

        // 遍历用户所有角色
        for (Role role : this.roles) {
            // 添加角色的菜单
            allMenus.addAll(role.getMenus());
        }

        // 将菜单按层级排序并返回
        return buildMenuHierarchy(allMenus);
    }

    private Set<Menu> buildMenuHierarchy(Set<Menu> menus) {
        // 按照parent_id构建菜单层级结构
        Set<Menu> topLevelMenus = menus.stream()
                .filter(menu -> menu.getParentMenu() == null) // 顶级菜单没有父菜单
                .collect(Collectors.toSet());

        // 给每个菜单添加子菜单
        for (Menu menu : topLevelMenus) {
            buildChildren(menu, menus);
        }

        return topLevelMenus;
    }

    private void buildChildren(Menu parentMenu, Set<Menu> allMenus) {
        // 获取所有子菜单并递归调用
        Set<Menu> children = allMenus.stream()
                .filter(menu -> parentMenu.equals(menu.getParentMenu())) // 找到所有属于该父菜单的子菜单
                .collect(Collectors.toSet());

        parentMenu.setChildMenus(children);  // 设置子菜单

        // 递归处理每个子菜单的子菜单
        for (Menu childMenu : children) {
            buildChildren(childMenu, allMenus);
        }
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", status=" + status +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        User user = (User) o;
        return id.equals(user.id);
    }

    @Override
    public int hashCode() {
        return id.hashCode();
    }
}
